// Modules to control application life and create native browser window
const { app, BrowserWindow, globalShortcut, Menu, Tray } = require('electron')
const path = require('path');
const fs = require('fs')
const startHtml = path.join(__dirname,"../render/startup/startup.html")
const icoPath = path.join(__dirname, "ico.png");
const windows = require('./windows');


//初始化功能模块
//遍历文件夹and导入
const lodaModules = () => {
  let primary = windows.getPlugins("primary");
  primary.forEach(r => {
    console.warn("加载了一个primary插件",r.key,r.path)
    require(r.path);
  })
}

const createWindow = () => {

  //启动屏
  {
    windows.startup = new BrowserWindow({
      width: 600,
      height: 260,
      frame: false,
      center: true,
      // alwaysOnTop: true,
      resizable: false,
      movable: false,
      transparent: true,
      icon: icoPath,
    });

    windows.startup.loadFile(startHtml);
  }
  //主窗口
  {
    windows.main = new BrowserWindow({
      width: 1080,
      height: 960,
      minWidth: 400,
      minHeight: 400,
      show: false,
      autoHideMenuBar: true,
      icon: icoPath,
      resizable: true,
      movable: true,
      title: `dnf-app`,
      webPreferences: {
        preload: path.join(__dirname, 'preload.js'),
        nodeIntegration: true,
        enableRemoteModule: true,
        contextIsolation: true,
        webSecurity: false  //跨域
      }
    })

    windows.main.on('close', () => {
      windows.main = null;
      windows.tray.destroy();
      windows.tray = null;
    })

    //注册全局快捷键
    globalShortcut.register('Ctrl+Shift+D', () => {
      // windows.startup.webContents.openDevTools({ mode: 'detach' }) //开启开发者工具
      windows.main.webContents.openDevTools({ mode: 'detach' }) //开启开发者工具
    })
  }

  //托盘
  {
    if (windows.tray == null) {
      windows.tray = new Tray(icoPath);

      const contextMenu = Menu.buildFromTemplate(
        [
          { label: '显示', click: function () { windows.main.show() } },
          { label: '退出', click: function () { app.quit() } }
        ]
      )
      windows.tray.setToolTip('dnf-app')
      windows.tray.setContextMenu(contextMenu)
      windows.tray.on("click", () => {
        windows.main.show()
      })
    }

  }

  windows.showMain();
}

app.whenReady().then(() => {
  lodaModules();
  createWindow()

  // app.on('activate', function () {
  //   if (BrowserWindow.getAllWindows().length === 0) {
  //     createWindow()
  //   }
  // })
})

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') {
    app.quit();
  }
})

//屏蔽安全警告
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'